package project;

import java.util.ArrayList;
import java.util.List;

public class ShoppingCart
{
  private static ShoppingCart instance = null;
  private ArrayList<ShoppingItem> items;
  private ArrayList<ShoppingCartListener> listeners;

  protected ShoppingCart()
  {
    this.items = new ArrayList();
    this.listeners = new ArrayList();
  }

  public static ShoppingCart getInstance()
  {
    if (instance == null) {
      instance = new ShoppingCart();
    }
    return instance;
  }

  public void addItem(ShoppingItem sci)
  {
    this.items.add(sci);
    fireShoppingCartChanged();
  }

  public void removeItem(ShoppingItem sci)
  {
    this.items.remove(sci);
    fireShoppingCartChanged();
  }

  public void addProduct(Product p)
  {
    this.items.add(new ShoppingItem(p));
    fireShoppingCartChanged();
  }

  public void addProduct(Product p, double d)
  {
    this.items.add(new ShoppingItem(p, d));
    fireShoppingCartChanged();
  }

  public void removeProduct(Product p)
  {
    List found = new ArrayList();

    for (ShoppingItem sci : this.items) {
      if (sci.getProduct().equals(p)) {
        found.add(sci);
      }
    }
    this.items.removeAll(found);
    fireShoppingCartChanged();
  }

  public void clear()
  {
    this.items.clear();
    fireShoppingCartChanged();
  }

  public List<ShoppingItem> getItems()
  {
    return this.items;
  }

  public double getTotal()
  {
    double total = 0.0D;

    for (ShoppingItem sci : this.items) {
      total += sci.getTotal();
    }
    return total;
  }

  public void addShoppingCartListener(ShoppingCartListener scl)
  {
    this.listeners.add(scl);
  }

  public void removeShoppingCartListener(ShoppingCartListener scl)
  {
    this.listeners.remove(scl);
  }

  private void fireShoppingCartChanged()
  {
    for (ShoppingCartListener scl : this.listeners)
      scl.shoppingCartChanged();
  }
}